<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  title: '',
  // ----
  power: 1,
  forSelf: Number(logUser.id) === Number(proxy.$route.query.dealer_id)
})
const addr = ref({})
// ----
const isNumber = /^([1-9]\d*|[0]{1,1})$/
const pdt = reactive({
  name: '',
  image: '',
  sizes: [],
  unit: '',
  total: 0,
  remark: ''
})

/* ---- */
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// ----
const getCurrencyInfo = async () => {
  if (Number(Object.keys(logUser).length) > 0) {
    // --获取当前用户权限信息--
    user.power = 2
    // --获取默认地址--
    let forAddrData = {
      params: {
        'AddressSearch[dealer_id]': logUser.id,
        'AddressSearch[is_default]': 1
      }
    }
    if (proxy.$route.query.addr_id) forAddrData = { params: { 'AddressSearch[id]': proxy.$route.query.addr_id } }
    await proxy.$http.get('address/index', forAddrData).then((res) => {
      if (res.items && Number(res.items.length) > 0) {
        const AData = res.items[0]
        // ----
        const forCitys = String(AData.province) === String(AData.city) ? AData.province + AData.district : AData.province + AData.city + AData.district
        const forAddress = Number(AData.address.indexOf(forCitys)) === Number(-1) ? forCitys + proxy.$Myfun.setText(AData.address) : proxy.$Myfun.setText(AData.address)
        // ----
        addr.value = {
          id: AData.id,
          name: proxy.$Myfun.setText(AData.name),
          telphone: AData.telphone,
          addrShow: forAddress,
          // ----
          dealer_id: AData.dealer_id,
          is_default: AData.is_default,
          province: AData.province,
          city: AData.city,
          district: AData.district,
          address: AData.address
        }
      }
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // --获取用户信息 & 计量单位 & 商品详情 --
  const forUserData = { params: { 'DealerSearch[id]': proxy.$route.query.dealer_id } }
  const forUnitData = {
    params: {
      'MeasuringUnitSearch[dealer_id]': proxy.$route.query.dealer_id,
      // --是否云仓计量单位--
      'MeasuringUnitSearch[is_store]': 0,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forGoodsData = { params: { 'ProductSearch[id]': proxy.$route.query.goods_id } }
  await proxy.$Axios.all([
    proxy.$Axios.get('dealer/index', forUserData),
    proxy.$Axios.get('measuring-unit/index', forUnitData),
    proxy.$Axios.get('proc/index', forGoodsData)
  ]).then(proxy.$Axios.spread((userData, unitData, goodsData) => {
    // --用户信息--
    const UData = userData.items[0] || {}
    proxy.$Myfun.getJsonData(UData.ads_content, (resJson) => {
      if (resJson[0].name) user.title = proxy.$Myfun.setText(resJson[0].name)
    })
    // --计量单位--
    const unitItems = []
    unitData.items.forEach((item, index) => {
      unitItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    // --商品详情--
    if (goodsData.items && Number(goodsData.items.length) > 0) {
      const GData = goodsData.items[0]
      // ----
      let forAdv = ''
      proxy.$Myfun.getJsonData(GData.img_top, (resJson) => { forAdv = resJson[0].image })
      // ----
      let forSize = []
      let forTotal = 0
      const sizeTtems = []
      proxy.$Myfun.getJsonData(GData.price_json, (resJson) => { forSize = resJson })
      forSize.forEach((item) => {
        sizeTtems.push({
          name: item.name,
          price: Number(item.price).toFixed(2),
          unit: item.unit,
          num: 1
        })
        forTotal += parseFloat(item.price) * 1
      })
      // ----
      pdt.name = proxy.$Myfun.setText(GData.name)
      pdt.image = forAdv
      pdt.sizes = sizeTtems
      pdt.total = forTotal.toFixed(2)
      // ----
      unitItems.some((current) => {
        if (String(current.value) === String(forSize[0].unit)) pdt.unit = current.text
      })
    } else { proxy.$Myfun.forToast(layer.value, 'open', '该商品已经下架啦！！！', () => { proxy.$router.back() }) }
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'UserAddress', { dealer_id: proxy.$route.query.dealer_id, goods_id: proxy.$route.query.goods_id, addr_back: 'GoodsCart' })
      break
    }
    case 2: {
      if (Number(pdt.sizes[item].num) <= 0) return false
      pdt.sizes[item].num--
      let forTotal = 0
      pdt.sizes.forEach((curItem, curIndex) => {
        forTotal += parseFloat(curItem.price) * Number(curItem.num)
      })
      pdt.total = forTotal.toFixed(2)
      break
    }
    case 3: {
      pdt.sizes[item].num++
      let forTotal = 0
      pdt.sizes.forEach((curItem, curIndex) => {
        forTotal += parseFloat(curItem.price) * Number(curItem.num)
      })
      pdt.total = forTotal.toFixed(2)
      break
    }
    case 4: {
      if (!isNumber.test(pdt.sizes[item].num)) pdt.sizes[item].num = 0
      let forTotal = 0
      pdt.sizes.forEach((curItem, curIndex) => {
        forTotal += parseFloat(curItem.price) * Number(curItem.num)
      })
      pdt.total = forTotal.toFixed(2)
      break
    }
  }
}
// ----
const setDefault = async (item) => {
  await proxy.$http.post('order-address/create', {
    order_id: item.id,
    dealer_id: addr.value.dealer_id,
    name: addr.value.name,
    telphone: addr.value.telphone,
    is_default: addr.value.is_default,
    province: addr.value.province,
    city: addr.value.city,
    district: addr.value.district,
    address: addr.value.address,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
// ----
const subform = async () => {
  if (!addr.value.id) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写收货地址！')
    return false
  }
  const sizeTtems = pdt.sizes.filter((item) => { return Number(item.num) > 0 })
  if (Number(sizeTtems.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '订购数量不能为零！')
    return false
  }
  // ----
  const forSize = JSON.stringify(sizeTtems)
  // ----
  const forType = 'post'
  const forUrl = 'order/create'
  const forData = {
    dealer_id: proxy.$route.query.dealer_id,
    to_dealer_id: logUser.id,
    type: 0,
    // ----
    product_id: proxy.$route.query.goods_id,
    pro_name: pdt.name,
    pro_json: forSize,
    total_price: pdt.total,
    remark: pdt.remark,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (resData) {
    await setDefault(resData)
    // ----
    proxy.$Myfun.disLoading(layerLoading.value, 'close')
    proxy.$router.back()
  } else {
    proxy.$Myfun.disLoading(layerLoading.value, 'close')
  }
  // --防止一次回退不成功--
  if (resData) proxy.$router.back()
}

/* ---- */
onMounted(() => {
  getCurrencyInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="PDV-addr xw-bg-white xw-radius-3" v-if="addr && Number(Object.keys(addr).length) > 0 && Number(user.power) === 2">
      <div class="PDV-addr-top xw-flex xw-flex-align">
        <em class="fa fa-compass xw-color-11"></em>
        <div class="xw-ellipsis-2 xw-flex-W1">{{addr.addrShow}}</div>
        <span class="xw-btn xw-WBlue" @click="getAuditFun(1)">编辑</span>
      </div>
      <div class="PDV-addr-fot xw-flex xw-flex-align xw-flex-justify">
        <div><em class="fa fa-user"></em>{{addr.name}}</div>
        <div><em class="fa fa-phone-volume"></em>{{addr.telphone}}</div>
      </div>
    </div>
    <div class="PDV-unAddr xw-bg-white xw-radius-3 xw-flex xw-flex-align" v-else >
      <em class="fa fa-compass xw-color-11"></em>
      <div class="xw-flex-W1">请填写收货地址</div>
      <span class="xw-btn xw-WBlue" @click="getAuditFun(1)">编辑</span>
    </div>
    <div class="PDV-pdt xw-flex xw-flex-align">
      <img class="PDV-img" :src="pdt.image" v-if="pdt.image"/>
      <div class="PDV-title xw-ellipsis-3 xw-flex-W1">{{pdt.name}}</div>
    </div>
    <ul class="list-size xw-flex xw-flex-column" v-if="pdt.sizes && Number(pdt.sizes.length) > 0">
      <li class="xw-bg-white xw-radius-3" v-for="(item, index) in pdt.sizes">
        <div class="LSE-top"><span class="xw-color-13">型号规格：</span>{{item.name}}</div>
        <div class="LSE-con xw-flex xw-flex-align xw-flex-justify">
          <div class="LSE-price xw-flex xw-flex-align">
            <span class="xw-color-13">单价：</span>
            <div class="xw-color-11">{{item.price}}</div>
            <span>元</span>
            <span v-if="pdt.unit">/{{pdt.unit}}</span>
          </div>
          <div class="LSE-info xw-flex xw-flex-align">
            <span class="xw-color-13">订购：</span>
            <a class="LSE-add" @click="getAuditFun(2, index)">－</a>
            <div class="LSE-num"><input class="text" placeholder="" @blur="getAuditFun(4, index)" v-model.trim="item.num"/></div>
            <a class="LSE-add" @click="getAuditFun(3, index)">＋</a>
          </div>
        </div>
      </li>
    </ul>
    <div class="PDV-desc">
      <div class="form-are xw-radius-3">
        <p><textarea class="tarea-H3" placeholder="订购说明" v-model.trim="pdt.remark"></textarea></p>
      </div>
    </div>
    <footer>
      <div class="tabs xw-foot-Tfg xw-flex xw-flex-align xw-flex-justify">
        <p class="xw-flex xw-flex-align">合计金额：<span class="xw-color-11">{{pdt.total}}</span>元</p>
        <div class="xw-act xw-bgCL-11" @click="subform" v-if="!user.forSelf">确认提交</div>
      </div>
    </footer>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.PDV-addr { margin: 1.2rem 1rem 0; padding: 1rem; border: 2px dashed #cccccc; }
.PDV-addr-top em { margin-right: 1rem; font-size: 2.4rem; }
.PDV-addr-top div { line-height: 2.5rem; font-size: 1.5rem; }
.PDV-addr-top span { margin-left: 1rem; }
.PDV-addr-fot { margin: 1rem 0 0; }
.PDV-addr-fot div { font-size: 1.5rem; }
.PDV-addr-fot div em { margin-right: 1rem; font-size: 1.6rem; color: #bbbbbb; }
.PDV-unAddr { margin: 1.2rem 1rem 0; padding: 1rem; border: 2px dashed #cccccc; }
.PDV-unAddr em { margin-right: 1rem; font-size: 2.4rem; }
.PDV-unAddr div { line-height: 2.5rem; font-size: 1.5rem; }
.PDV-pdt { margin: 1.2rem 1rem 0; }
.PDV-img { margin: 0 1rem 0 0; width: 7.5rem; height: 7.5rem; }
.PDV-title { line-height: 2.5rem; font-size: 1.7rem; }
.list-size li { position: relative; margin: 1rem 1rem 0; padding: 1rem; overflow: hidden; }
.LSE-top { line-height: 2.5rem; }
.LSE-add { width: 3rem; height: 3rem; line-height: 3rem; text-align: center; }
.LSE-num { padding: 0 0.5rem; width: 6rem; height: 3rem; line-height: 3rem; border: 1px solid #d7d7d7; }
.LSE-num input { text-align: center; font-size: 1.4rem; }
.PDV-desc { margin: 1rem 1rem 6.4rem; }

/* ---- */
.tabs { height: 5rem; }
.tabs p { margin: 0 1rem; font-size: 1.6rem; }
.tabs p span { font-size: 1.8rem; }
.tabs div { padding: 0 1rem; height: 5rem; line-height: 5rem; font-size: 1.6rem; }
</style>
